package net.bwie.vehicle.dws.function;

import net.bwie.realtime.guanjuntao.util.DateTimeUtil;
import net.bwie.vehicle.dws.bean.BatteryHealthData;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class BatteryHealthWindowFunction implements WindowFunction<BatteryHealthData, String, String, TimeWindow> {


    @Override
    public void apply(String s, TimeWindow window, Iterable<BatteryHealthData> input, Collector<String> out) throws Exception {
        // 将窗口开始时间转换为字符串格式
        String startTime = DateTimeUtil.convertLongToString(window.getStart(), DateTimeUtil.DATE_TIME_FORMAT);
      // 将窗口结束时间转换为字符串格式
        String endTime = DateTimeUtil.convertLongToString(window.getEnd(), DateTimeUtil.DATE_TIME_FORMAT);

       // 初始化计数器，用于统计vin元素的数量
        double count = 0;
       // 初始化总和变量，用于累加充满电状态下的容量
        double sum = 0;

       // 遍历所有BatteryHealthData元素
        for (BatteryHealthData element : input) {
            // 每遍历到一个元素，计数器加1
            count++;
            // 累加当前元素的满电荷容量到总和变量
            sum += element.getFullChargeCapacity();
        }

      // 构造输出字符串，包含窗口时间范围、元素数量、满电荷容量总和、平均满电荷容量和当前时间戳
        String output = startTime + "," + endTime + ","
                + count + "," + sum + "," + (sum / count) + ","
                + System.currentTimeMillis();

       // 输出处理结果
        out.collect(output);

    }
}
